package models

import (
	"cubeAdmin/dto"
	"fmt"
	"github.com/beego/beego/v2/client/orm"
)

type SysConfig struct {
	Id       int    `orm:"column(id);auto" json:"id"`
	Name     string `orm:"column(name);size(128)" json:"name" description:"配置名称"`
	Sort     int    `orm:"column(sort);null" json:"sort"`
	CreateBy int64  `orm:"column(create_by);null" json:"createBy"`
	UpdateBy int64  `orm:"column(update_by);null" json:"updateBy"`
	BaseModel
}

func (t *SysConfig) TableName() string {
	return "sys_config"
}

func init() {
	orm.RegisterModel(new(SysConfig))
}

// AddSysConfig insert a new SysConfig into database and returns
// last inserted Id on success.
func AddSysConfig(m *SysConfig) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	return
}

// GetSysConfigById retrieves SysConfig by Id. Returns error if
// Id doesn't exist
func GetSysConfigById(id int) (v *SysConfig, err error) {
	o := orm.NewOrm()
	v = &SysConfig{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

func (*SysConfig) GetList(req dto.ConfigPageReq) ([]SysConfig, int64, error) {
	// 初始化查询实例
	query := orm.NewOrm().QueryTable(new(SysConfig)).Filter("is_del", 0)
	// 配置名称查询
	if req.Name != "" {
		query = query.Filter("name__contains", req.Name)
	}
	// 排序
	query = query.OrderBy("sort")
	// 查询总数
	count, err := query.Count()
	//// 分页设置
	//offset := (req.Page - 1) * req.Limit
	//query = query.Limit(req.Limit, offset)
	// 查询列表
	lists := make([]SysConfig, 0)
	query.All(&lists)
	// 返回结果
	return lists, count, err
}

// UpdateSysConfigById UpdateSysConfig updates SysConfig by Id and returns error if
// the record to be updated doesn't exist
func UpdateSysConfigById(m *SysConfig) (err error) {
	o := orm.NewOrm()
	v := SysConfig{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteSysConfig deletes SysConfig by Id and returns error if
// the record to be deleted doesn't exist
func DeleteSysConfig(id int) (err error) {
	o := orm.NewOrm()
	v := SysConfig{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&SysConfig{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}
